const crypto = require('crypto') ;
const db = uniCloud.database();
const User = db.collection("uni-id-users");


module.exports = {
	handle : [] , //拦截的路径，此处留空表示拦截全部的路径
	clear : [ //配置要清除拦截器的路径，注意：如果配置了handle则此处的配置无效。
		"user-center/user/login", 
		"user-center/user/checkToken"
	] , 
	invoke : async function (){
		const {event , ctx } = this ;
		var res = await checkToken(event.uniIdToken , this.configs.uniId );
		if(res.code){
			return {
				state : 'needLogin',
				msg : "请登录"
			};
		}
		//将user传入下一个拦截器，在拦截器函数的参数中可以获取到，也可以通过this.getAttr("user")来取到该值。
		this.setAttr({user : res.userInfo}); 
		//当前拦截器放行
		this.next();
	}
} ;

/**
 * 获取客户端User-Agent
 */
function getClientUaHash () {
	const hashContent = /MicroMessenger/i.test(__ctx__.CLIENTUA) ? __ctx__.CLIENTUA.split(' Process/appbrand')[0] : __ctx__.CLIENTUA ;
    return uniCloud.baseCloud.md5(hashContent);
}

async function checkToken(token , config) {
	let baseCloud = uniCloud.baseCloud ;
	try {
	  const payload = baseCloud.jwt.decode(token, config.tokenSecret ) ;
	  if ( config.bindTokenToDevice && payload.clientId !== getClientUaHash()) {
		return {
		  code: 30201,
		  msg: 'token不合法，请重新登录'
		}
	  }

	  const userInfo = baseCloud.findFirst(await User.doc(payload.uid).get()) ;

	  if ( null == userInfo || !userInfo.token) {
		return {
		  code: 30202,
		  msg: 'token不合法，请重新登录'
		}
	  }
	  if (userInfo.status === 1) {
		return {
		  code: 10001,
		  msg: '账号已禁用'
		}
	  }
	  let tokenList = userInfo.token
	  if (typeof tokenList === 'string') {
		tokenList = [tokenList]
	  }
	  if (tokenList.indexOf(token) === -1) {
		return {
		  code: 30202,
		  msg: 'token不合法，请重新登录'
		}
	  }

	  uniCloud.logger.log('checkToken payload', payload)

	  return {
		code: 0,
		msg: 'token校验通过',
		...payload,
		userInfo
	  }
	} catch (err) {
		console.log(err);
	  if (err.name === 'TokenExpiredError') {
		return {
		  code: 30203,
		  msg: 'token已过期，请重新登录',
		  err: err
		}
	  }

	  return {
		code: 30204,
		msg: '非法token',
		err: err
	  }
	}
}